<template>
  <div class="tactical-env-container">
    <div class="page-header">
      <div class="header-content">
        <h2>战术环境管理</h2>
        <!-- <p>管理和配置战术训练环境</p> -->
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          创建环境
        </el-button>
      </div>
    </div>

    <div class="content-wrapper">
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="环境名称">
            <el-input 
              v-model="filterForm.name" 
              placeholder="请输入环境名称"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="环境状态">
            <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
              <el-option label="运行中" value="running" />
              <el-option label="已停止" value="stopped" />
              <el-option label="部署中" value="deploying" />
              <el-option label="故障" value="error" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-section">
        <el-table
          :data="tableData"
          v-loading="loading"
          stripe
          border
        >
          <el-table-column prop="name" label="环境名称" width="200" />
          <el-table-column prop="type" label="环境类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column prop="updateTime" label="更新时间" width="160" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">

              <el-tooltip content="查看详情" placement="top" show-after="1000">
                <el-button type="primary" link @click="handleSee(row)">
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="编辑" placement="top" show-after="1000">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="启动" placement="top" show-after="1000" v-if="row.status === 'stopped'" >
                <el-button type="primary" link @click="startEnvironment(row)">
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="停止" placement="top" show-after="1000" v-if="row.status === 'running'" >
                <el-button type="primary" link @click="stopEnvironment(row)">
                  <el-icon><VideoPause /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="删除" placement="top" show-after="1000">
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 弹框 -->
    <el-dialog
      :title="viewDetail.title"
      v-model="viewDetail.open"
      width="1200px"
      append-to-body
    >
     <create :id="viewDetail.form.id" :isEdit="viewDetail.disabled" @cancel="viewDetail.cancel"></create>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Stopwatch, VideoPause, VideoPlay } from '@element-plus/icons-vue'
import create from './components/create.vue'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])

// 筛选表单
const filterForm = reactive({
  name: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 模拟数据
const mockData = [
  {
    id: 1,
    name: '红蓝对抗环境-01',
    type: '攻防对抗',
    status: 'running',
    description: '模拟企业内网环境，包含多个子网和服务器',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-20 14:20:00'
  },
  {
    id: 2,
    name: '渗透测试环境-02',
    type: '单兵作战',
    status: 'stopped',
    description: '包含常见漏洞的Web应用环境',
    createTime: '2024-01-16 09:15:00',
    updateTime: '2024-01-18 16:45:00'
  },
  {
    id: 3,
    name: '协同作战环境-03',
    type: '系统协同',
    status: 'deploying',
    description: '多人协作的大型网络环境',
    createTime: '2024-01-17 11:00:00',
    updateTime: '2024-01-17 11:00:00'
  }
]

// 生命周期
onMounted(() => {
  fetchData()
})

// 方法
const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const resetFilter = () => {
  filterForm.name = ''
  filterForm.status = ''
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchData()
}


const startEnvironment = (row) => {
  ElMessageBox.confirm('确认启动此环境吗？', '启动确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('环境启动中...')
    row.status = 'deploying'
    setTimeout(() => {
      row.status = 'running'
      ElMessage.success('环境启动成功')
    }, 3000)
  })
}

const stopEnvironment = (row) => {
  ElMessageBox.confirm('确认停止此环境吗？', '停止确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('环境停止中...')
    row.status = 'stopped'
    ElMessage.success('环境已停止')
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除环境"${row.name}"吗？此操作不可恢复。`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  })
}

// 工具函数
const getStatusTagType = (status) => {
  const statusMap = {
    running: 'success',
    stopped: 'info',
    deploying: 'warning',
    error: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    running: '运行中',
    stopped: '已停止',
    deploying: '部署中',
    error: '故障'
  }
  return statusMap[status] || '未知'
}

const getTypeTagType = (type) => {
  const typeMap = {
    '攻防对抗': 'danger',
    '单兵作战': 'success',
    '系统协同': 'warning'
  }
  return typeMap[type] || 'info'
}

const handleCreate = () => {
  viewDetail.value.title = "创建战术环境";
  viewDetail.value.disabled = false;
  viewDetail.value.open = true;
  viewDetail.value.form = {};
};

const handleSee = (row) => {
  viewDetail.value.title = "查看战术环境";
  viewDetail.value.disabled = true;
  viewDetail.value.open = true;
  viewDetail.value.form = row;
};
const handleEdit = (row) => {
  viewDetail.value.title = "编辑战术环境";
  viewDetail.value.disabled = false;
  viewDetail.value.open = true;
  viewDetail.value.form = row;
  viewDetail.value.buttons = [
    { type: "default", text: "取消", prop: "cancel" },
    { type: "primary", text: "提交", prop: "submit" },
  ];
};
const viewDetail =ref({
  title:"",
  disabled:false,
  open:false,
  form:null,
  cancel: () => {
    viewDetail.value.open = false;
  },
})
</script>

<style lang="scss" scoped>
.tactical-env-container {
  background-color: var(--bg-color);
}

  .header-content {
    h2 {
      margin: 0 0 8px 0;
      color: var(--text-color);
      font-size: 24px;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: var(--text-color-secondary);
      font-size: 14px;
    }
  }


.content-wrapper {
  background: var(--card-bg);
  border-radius: 8px;
  box-shadow: var(--card-shadow);
}

.filter-section {
  border-bottom: 1px solid var(--border-color);
}

.table-section {
  padding: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 